﻿using HDLogCenter.Infrastructure.Config;
using HDLogCenter.Infrastructure.Models;
using Hilink.RabbitMQSDK;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;

namespace HDLogCenter.Infrastructure.ExternalServices
{
    public class RabbitMQService: IDisposable
    {
        private readonly ushort PullCountMax = 1000;
        private readonly Consumer _logMsgConsumer;
        private readonly RMQConsumerConfig _options;
        public RabbitMQService(IOptionsMonitor<RMQConsumerConfig> options)
        {
            _options = options.CurrentValue;
            var logConsumerConfigInfo = new ConsumerConfigInfo()
            {
                ExchangeName = _options.Exchange,
                PrefetchCount = PullCountMax,
                QueueDurable = true,
                QueueName = _options.QueueName,
                RoutingKey = _options.RoutingKey
            };
            _logMsgConsumer = new Consumer(_options.Uri, logConsumerConfigInfo);
        }

        public List<AppLogModel> PullLogMessageFromQueue()
            => PullLogMessages(_logMsgConsumer);

        private List<AppLogModel> PullLogMessages(Consumer consumer)
        {
            var messages = new List<AppLogModel>();
            int count = 0;

            while (count < PullCountMax)
            {
                try
                {
                    if (consumer.Receive(out string message, out string routingKey))
                    {
                        var dto = JsonConvert.DeserializeObject<AppLogModel>(message);
                        if (dto != null)
                        {
                            messages.Add(dto);
                            count++;
                        }
                    }
                    else
                    {
                        break; // 队列中没消息了
                    }
                }
                catch (Exception ex)
                {
                    break;
                }
            }
            return messages;
        }

        public void Dispose()
        {
            _logMsgConsumer?.Dispose();
        }
    }
}
